/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.archive.portlet;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

import org.apache.commons.fileupload.FileItem;

import cn.com.chinasoa.archive.runtime.ArchiveRuntime;
import cn.com.chinasoa.archive.runtime.util.CharUtil;

import com.x4ee.soa.portal.framework.core.ActionConfig;
import com.x4ee.soa.portal.framework.core.ActionFilter;
import com.x4ee.soa.portal.framework.core.BaseRequestFilter;
import com.x4ee.soa.portal.framework.tools.PortletUploadFormParser;

/**
 * 上传文档
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-8-2下午02:26:51
 */
public class ArchiveUploadActionFilter extends BaseRequestFilter implements
		ActionFilter {

	public String process(ActionRequest actionRequest, ActionResponse actionResponse,
			ActionConfig actionConfig) throws PortletException, IOException {

		PortletUploadFormParser portletuploadFormParser = new PortletUploadFormParser(actionRequest,"UTF-8",0);
		String archiveTitle = portletuploadFormParser.getParamValue(ArchiveUploadHelper.ARCHIVE_TITLE);
		archiveTitle = CharUtil.iso2gbutf8(archiveTitle);
		Map fileMap = portletuploadFormParser.getFileMap();
		Set keySet = fileMap.keySet();

		if((keySet!=null)&&(!keySet.isEmpty())){
			Object archiveFileObj= fileMap.get(keySet.iterator().next());
			if((archiveFileObj!=null)&&(archiveFileObj instanceof FileItem)){
				FileItem archiveFile = (FileItem)archiveFileObj;
				boolean result = ArchiveRuntime.storeArchive(
						actionRequest,ArchiveRuntime.getRepository(actionRequest),
						ArchiveUploadActionFilter.getFileName(archiveFile.getName()),
						archiveTitle,
						archiveFile.getInputStream(),
						actionRequest.getRemoteUser());
				if(result)return ArchiveUploadHelper.SUCCESS;
			}
		}
		return ArchiveUploadHelper.ERROR;
	}
	
	public static String getFileName(String fullname){
		String filename = fullname;
		if(filename.indexOf(File.separator)>-1){
			filename=filename.substring(filename.lastIndexOf(File.separator)+1,filename.length());
		}
		return filename;
	}

}
